// 增强版BOSS系统 - 超级挑战
class EnhancedBoss {
    constructor(x, y, type = 'ultimate_principal') {
        try {
            this.x = x || 500;
            this.y = y || 375;
            this.type = type;
            this.radius = 50; // 更大的BOSS
            
            const stats = this.getBossStats(this.type);
            this.health = stats.health;
            this.maxHealth = this.health;
            this.speed = stats.speed;
            this.damage = stats.damage;
            
            // 多阶段系统
            this.phase = 1;
            this.maxPhase = 4;
            this.phaseTransitioning = false;
            this.phaseTransitionTime = 0;
            
            // 状态系统
            this.state = 'spawning';
            this.stateTimer = 0;
            this.lastAttackTime = 0;
            // 地狱模式攻击冷却时间大幅缩短
            this.attackCooldown = stats.hellModeBonus ? 800 : 1500; // 地狱模式下更频繁的攻击
            
            // 特殊技能冷却 - 地狱模式下大幅缩短
            const cooldownMultiplier = stats.hellModeBonus ? stats.hellModeBonus.skillCooldownReduction : 1;
            this.skillCooldowns = {
                summonZombies: 0,
                projectileBarrage: 0,
                teleport: 0,
                rage: 0,
                healAura: 0,
                shockwave: 0,
                meteor: 0,
                clone: 0,
                ultimateAttack: 0,
                desperateAssault: 0
            };
            this.baseCooldowns = {
                summonZombies: Math.floor(8000 * cooldownMultiplier),
                projectileBarrage: Math.floor(6000 * cooldownMultiplier),
                teleport: Math.floor(10000 * cooldownMultiplier),
                rage: Math.floor(15000 * cooldownMultiplier),
                healAura: Math.floor(20000 * cooldownMultiplier),
                shockwave: Math.floor(12000 * cooldownMultiplier),
                meteor: Math.floor(18000 * cooldownMultiplier),
                clone: Math.floor(25000 * cooldownMultiplier),
                ultimateAttack: Math.floor(30000 * cooldownMultiplier),
                desperateAssault: Math.floor(5000 * cooldownMultiplier)
            };
            
            // 动画和视觉
            this.animationFrame = 0;
            this.animationTime = 0;
            this.size = 80;
            this.facing = 0;
            
            // 特殊效果 - 地狱模式增强
            this.aura = { 
                radius: 0, 
                color: stats.hellModeBonus ? '#FF4500' : '#FF0000', // 地狱模式下更亮的光环
                alpha: 0.7,
                pulseSpeed: stats.hellModeBonus ? 4 : 2 // 地狱模式下更快的脉冲
            };
            this.isInvulnerable = true;
            this.spawnTime = Date.now();
            this.spawnDuration = 3000;
            
            // 召唤物管理 - 地狱模式增强
            this.minions = [];
            this.maxMinions = stats.hellModeBonus ? 15 : 8; // 地狱模式下更多召唤物
            this.clones = [];
            this.maxClones = stats.hellModeBonus ? 4 : 2; // 地狱模式下更多分身
            
            // 地狱模式特殊属性
            this.isHellMode = !!stats.hellModeBonus;
            this.hellModeBonus = stats.hellModeBonus;
            
            // 攻击模式
            this.attackPatterns = ['melee', 'ranged', 'special', 'combo'];
            this.currentPattern = 0;
            this.patternTimer = 0;
            
            // 移动模式
            this.movementMode = 'chase';
            
            // 动画效果
            this.animationTime = 0;
            this.breathingScale = 1.0;
            this.floatOffset = 0;
            this.eyeBlinkTimer = 0;
            this.eyesOpen = true;
            this.shadowPulse = 0;
            this.bloodDrops = [];
            this.energyParticles = [];
            this.teleportCharges = 3;
            
            console.log(`💀 增强版BOSS创建: ${this.type}, 血量: ${this.health}, 阶段: ${this.maxPhase}`);
            
        } catch (error) {
            console.error('增强BOSS创建失败:', error);
            throw error;
        }
    }
    
    getBossStats(type) {
        return {
            'ultimate_principal': {
                name: '终极校长BOSS【地狱模式】',
                health: 3000, // 大幅增加血量到3000
                speed: 120, // 增加移动速度
                damage: 100, // 大幅增加伤害
                color: '#8B0000',
                resistances: {
                    physical: 0.4, // 增加到40%物理抗性
                    fire: 0.3, // 增加火焰抗性
                    ice: 0.3, // 增加冰冻抗性
                    explosive: 0.5 // 新增爆炸抗性
                },
                // 新增地狱模式特性
                hellModeBonus: {
                    phaseHealthMultiplier: 1.2, // 每阶段额外20%血量
                    attackSpeedBonus: 0.5, // 攻击速度增加50%
                    skillCooldownReduction: 0.6 // 技能冷却减少40%
                }
            }
        }[type] || {
            name: '未知BOSS',
            health: 1000,
            speed: 60,
            damage: 50,
            color: '#FF0000'
        };
    }
    
    update(deltaTime, player) {
        try {
            if (!player) return;
            
            // 更新技能冷却
            this.updateCooldowns(deltaTime);
            
            // 更新状态
            this.updateBossState(deltaTime, player);
            
            // 更新阶段
            this.updatePhase();
            
            // 更新召唤物
            this.updateMinions(deltaTime, player);
            
            // 更新动画和特效
            this.updateAnimations(deltaTime);
            
            // 检查死亡
            this.checkDeath();
            
        } catch (error) {
            console.error('BOSS更新失败:', error);
        }
    }
    
    updateCooldowns(deltaTime) {
        Object.keys(this.skillCooldowns).forEach(skill => {
            if (this.skillCooldowns[skill] > 0) {
                this.skillCooldowns[skill] -= deltaTime;
            }
        });
    }
    
    updateBossState(deltaTime, player) {
        const currentTime = Date.now();
        const distToPlayer = this.getDistanceToPlayer(player);
        
        // 处理生成状态
        if (this.state === 'spawning') {
            if (currentTime - this.spawnTime > this.spawnDuration) {
                this.state = 'active';
                this.isInvulnerable = false;
                console.log('💀 BOSS激活！准备战斗！');
            }
            return;
        }
        
        // 阶段转换状态
        if (this.phaseTransitioning) {
            this.handlePhaseTransition(deltaTime);
            return;
        }
        
        // 主要AI逻辑
        this.stateTimer += deltaTime;
        
        switch (this.state) {
            case 'active':
                this.handleActiveState(deltaTime, player, distToPlayer);
                break;
            case 'attacking':
                this.handleAttackState(deltaTime, player);
                break;
            case 'special':
                this.handleSpecialState(deltaTime, player);
                break;
            case 'enraged':
                this.handleEnragedState(deltaTime, player);
                break;
        }
    }
    
    handleActiveState(deltaTime, player, distToPlayer) {
        // 移动向玩家
        if (distToPlayer > 100) {
            this.moveTowardsPlayer(deltaTime, player);
        }
        
        // 近距离攻击检查 - 优先级最高
        if (distToPlayer <= 80) {
            const currentTime = Date.now();
            if (currentTime - this.lastAttackTime > this.attackCooldown) {
                this.performMeleeAttack(player);
                this.lastAttackTime = currentTime;
            }
        }
        
        // 决定下一个行动
        const actionInterval = this.state === 'enraged' ? 1000 : 2000; // 愤怒时更频繁
        if (this.stateTimer > actionInterval) {
            const actions = this.getAvailableActions();
            const action = actions[Math.floor(Math.random() * actions.length)];
            this.executeAction(action, player);
            this.stateTimer = 0;
        }
        
        // 检查是否应该进入愤怒状态
        if (this.health / this.maxHealth < 0.3 && this.phase >= 3 && this.state !== 'enraged') {
            this.enterEnragedMode();
        }
    }
    
    getAvailableActions() {
        const actions = ['attack', 'move'];
        
        // 根据阶段添加可用技能
        if (this.phase >= 2) {
            if (this.skillCooldowns.projectileBarrage <= 0) actions.push('projectile_barrage');
            if (this.skillCooldowns.summonZombies <= 0) actions.push('summon');
        }
        
        if (this.phase >= 3) {
            if (this.skillCooldowns.teleport <= 0) actions.push('teleport');
            if (this.skillCooldowns.shockwave <= 0) actions.push('shockwave');
        }
        
        if (this.phase >= 4) {
            if (this.skillCooldowns.meteor <= 0) actions.push('meteor');
            if (this.skillCooldowns.clone <= 0 && this.clones.length < this.maxClones) actions.push('clone');
            // 终极阶段的超级技能
            if (this.skillCooldowns.ultimateAttack <= 0) actions.push('ultimate_combo');
        }
        
        // 根据血量百分比调整行动倾向
        const healthPercent = this.health / this.maxHealth;
        if (healthPercent < 0.5) {
            // 低血量时更激进
            if (this.skillCooldowns.projectileBarrage <= 0) actions.push('projectile_barrage');
            if (this.skillCooldowns.teleport <= 0) actions.push('teleport');
        }
        
        if (healthPercent < 0.25) {
            // 极低血量时疯狂技能释放
            actions.push('desperate_assault');
        }
        
        return actions;
    }
    
    executeAction(action, player) {
        switch (action) {
            case 'attack':
                this.performMeleeAttack(player);
                break;
            case 'projectile_barrage':
                this.performProjectileBarrage(player);
                break;
            case 'summon':
                this.summonMinions();
                break;
            case 'teleport':
                this.performTeleport(player);
                break;
            case 'shockwave':
                this.performShockwave();
                break;
            case 'meteor':
                this.performMeteorAttack(player);
                break;
            case 'clone':
                this.createClone();
                break;
            case 'ultimate_combo':
                this.performUltimateCombo(player);
                break;
            case 'desperate_assault':
                this.performDesperateAssault(player);
                break;
            case 'move':
                this.changeMovementPattern();
                break;
        }
    }
    
    // 近战攻击
    performMeleeAttack(player) {
        const distToPlayer = this.getDistanceToPlayer(player);
        if (distToPlayer < 80) {
            const damage = this.damage + (this.phase - 1) * 15; // 阶段越高伤害越高
            this.dealDamageToPlayer(player, damage);
            
            // 创建冲击波特效
            this.createShockwaveEffect(this.x, this.y, 50);
            
        }
        this.lastAttackTime = Date.now();
    }
    
    // 投射物弹幕
    performProjectileBarrage(player) {
        const projectileCount = 8 + this.phase * 2; // 阶段越高投射物越多
        
        for (let i = 0; i < projectileCount; i++) {
            const angle = (i / projectileCount) * Math.PI * 2;
            const speed = 250;
            
            const projectile = {
                x: this.x,
                y: this.y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                damage: this.damage * 0.6,
                radius: 8,
                life: 3000,
                maxLife: 3000,
                type: 'boss_projectile',
                color: '#FF4400'
            };
            
            this.addBossProjectile(projectile);
        }
        
        this.skillCooldowns.projectileBarrage = 6000;
        console.log(`💀 BOSS发射弹幕！投射物数量: ${projectileCount}`);
    }
    
    // 召唤小怪
    summonMinions() {
        const summonCount = Math.min(3, this.maxMinions - this.minions.length);
        
        for (let i = 0; i < summonCount; i++) {
            const angle = (i / summonCount) * Math.PI * 2;
            const distance = 80;
            const x = this.x + Math.cos(angle) * distance;
            const y = this.y + Math.sin(angle) * distance;
            
            // 创建小僵尸
            const minion = this.createMinion(x, y);
            this.minions.push(minion);
            
            // 添加到游戏世界
            if (window.gameEngine && window.gameEngine.zombies) {
                window.gameEngine.zombies.push(minion);
            }
        }
        
        this.skillCooldowns.summonZombies = 8000;
        console.log(`💀 BOSS召唤了 ${summonCount} 个小怪！`);
    }
    
    // 瞬移
    performTeleport(player) {
        if (this.teleportCharges <= 0) return;
        
        // 选择新位置（远离玩家或包围玩家）
        const canvas = document.getElementById('gameCanvas');
        const canvasWidth = canvas ? canvas.width : 1000;
        const canvasHeight = canvas ? canvas.height : 750;
        
        let newX, newY;
        if (Math.random() < 0.5) {
            // 远离玩家
            const angle = Math.atan2(this.y - player.y, this.x - player.x);
            newX = player.x + Math.cos(angle) * 200;
            newY = player.y + Math.sin(angle) * 200;
        } else {
            // 随机位置
            newX = 100 + Math.random() * (canvasWidth - 200);
            newY = 100 + Math.random() * (canvasHeight - 200);
        }
        
        // 边界检查
        newX = Math.max(50, Math.min(canvasWidth - 50, newX));
        newY = Math.max(50, Math.min(canvasHeight - 50, newY));
        
        // 瞬移特效
        this.createTeleportEffect(this.x, this.y);
        
        this.x = newX;
        this.y = newY;
        this.teleportCharges--;
        
        // 瞬移后特效
        this.createTeleportEffect(this.x, this.y);
        
        this.skillCooldowns.teleport = 5000;
        console.log(`💀 BOSS瞬移！剩余次数: ${this.teleportCharges}`);
    }
    
    // 冲击波攻击
    performShockwave() {
        const shockwaveRadius = 150 + this.phase * 25;
        
        // 对范围内玩家造成伤害
        if (window.player) {
            const distToPlayer = this.getDistanceToPlayer(window.player);
            if (distToPlayer < shockwaveRadius) {
                const damage = this.damage * 0.8;
                this.dealDamageToPlayer(window.player, damage);
            }
        }
        
        // 创建视觉效果
        this.createShockwaveEffect(this.x, this.y, shockwaveRadius);
        
        this.skillCooldowns.shockwave = 7000;
    }
    
    // 流星攻击
    performMeteorAttack(player) {
        const meteorCount = 3 + this.phase;
        
        for (let i = 0; i < meteorCount; i++) {
            setTimeout(() => {
                // 预测玩家位置
                const targetX = player.x + (Math.random() - 0.5) * 100;
                const targetY = player.y + (Math.random() - 0.5) * 100;
                
                // 创建流星警告
                this.createMeteorWarning(targetX, targetY);
                
                // 2秒后造成伤害
                setTimeout(() => {
                    this.createMeteorImpact(targetX, targetY);
                }, 2000);
                
            }, i * 500);
        }
        
        this.skillCooldowns.meteor = 12000;
        console.log(`💀 BOSS召唤流星雨！数量: ${meteorCount}`);
    }
    
    // 创建分身
    createClone() {
        const angle = Math.random() * Math.PI * 2;
        const distance = 120;
        const cloneX = this.x + Math.cos(angle) * distance;
        const cloneY = this.y + Math.sin(angle) * distance;
        
        const clone = {
            x: cloneX,
            y: cloneY,
            radius: this.radius * 0.8,
            health: this.maxHealth * 0.3,
            maxHealth: this.maxHealth * 0.3,
            damage: this.damage * 0.7,
            speed: this.speed * 1.2,
            isClone: true,
            lifespan: 15000, // 15秒存活时间
            creationTime: Date.now()
        };
        
        this.clones.push(clone);
        this.skillCooldowns.clone = 15000;
        console.log('💀 BOSS创建了分身！');
    }
    
    // 终极连击技能 - 第4阶段专属
    performUltimateCombo(player) {
        console.log('💀💀💀 BOSS释放终极连击！！！');
        this.skillCooldowns.ultimateAttack = 20000; // 20秒冷却
        
        // 连续技能组合：瞬移 -> 冲击波 -> 投射物弹幕 -> 流星
        let comboStep = 0;
        const comboInterval = setInterval(() => {
            try {
                switch (comboStep) {
                    case 0:
                        this.performTeleport(player);
                        break;
                    case 1:
                        this.performSuperShockwave();
                        break;
                    case 2:
                        this.performBulletHell(player);
                        break;
                    case 3:
                        this.performMeteorStorm(player);
                        clearInterval(comboInterval);
                        break;
                }
                comboStep++;
            } catch (comboError) {
                console.error('终极连击执行错误:', comboError);
                clearInterval(comboInterval);
            }
        }, 1500); // 每1.5秒执行一步
    }
    
    // 绝望突击 - 低血量时的疯狂技能
    performDesperateAssault(player) {
        console.log('💀💀💀 BOSS进入绝望突击模式！！！');
        this.skillCooldowns.desperateAssault = 15000; // 15秒冷却
        
        // 短时间内疯狂释放技能
        const assaultDuration = 8000; // 8秒持续时间
        const startTime = Date.now();
        
        const assaultLoop = () => {
            try {
                if (Date.now() - startTime > assaultDuration) {
                    console.log('绝望突击结束');
                    return;
                }
                
                // 随机选择技能疯狂释放
                const desperateSkills = ['projectile_barrage', 'shockwave', 'summon', 'teleport'];
                const randomSkill = desperateSkills[Math.floor(Math.random() * desperateSkills.length)];
                
                switch (randomSkill) {
                    case 'projectile_barrage':
                        this.performProjectileBarrage(player);
                        break;
                    case 'shockwave':
                        this.performShockwave();
                        break;
                    case 'summon':
                        this.summonMinions();
                        break;
                    case 'teleport':
                        this.performTeleport(player);
                        break;
                }
                
                // 继续下一轮
                setTimeout(assaultLoop, 800); // 每0.8秒一次技能
                
            } catch (assaultError) {
                console.error('绝望突击执行错误:', assaultError);
            }
        };
        
        assaultLoop();
    }
    
    // 超级冲击波（增强版）
    performSuperShockwave() {
        const shockwaveRadius = 250; // 更大范围
        
        // 多层冲击波
        for (let layer = 1; layer <= 3; layer++) {
            setTimeout(() => {
                // 对范围内玩家造成伤害
                if (window.player) {
                    const distToPlayer = this.getDistanceToPlayer(window.player);
                    if (distToPlayer < shockwaveRadius) {
                        const damage = this.damage * 1.2 * layer; // 每层伤害递增
                        this.dealDamageToPlayer(window.player, damage);
                    }
                }
                
                // 创建视觉效果
                this.createSuperShockwaveEffect(this.x, this.y, shockwaveRadius * layer * 0.6);
            }, layer * 500);
        }
        
    }
    
    // 弹幕地狱
    performBulletHell(player) {
        const projectileCount = 24; // 更多投射物
        const rings = 3; // 3圈弹幕
        
        for (let ring = 0; ring < rings; ring++) {
            setTimeout(() => {
                for (let i = 0; i < projectileCount; i++) {
                    const angle = (i / projectileCount) * Math.PI * 2 + (ring * Math.PI / 6);
                    const speed = 200 + ring * 50;
                    
                    const projectile = {
                        x: this.x,
                        y: this.y,
                        vx: Math.cos(angle) * speed,
                        vy: Math.sin(angle) * speed,
                        damage: this.damage * 0.8,
                        radius: 10,
                        life: 4000,
                        maxLife: 4000,
                        type: 'boss_hell_bullet',
                        color: '#FF0066',
                        priority: 'high'
                    };
                    
                    this.addBossProjectile(projectile);
                }
            }, ring * 300);
        }
        
        console.log('💀 BOSS释放弹幕地狱！');
    }
    
    // 流星暴雨
    performMeteorStorm(player) {
        const meteorCount = 8;
        
        for (let i = 0; i < meteorCount; i++) {
            setTimeout(() => {
                // 更广泛的攻击范围
                const targetX = player.x + (Math.random() - 0.5) * 200;
                const targetY = player.y + (Math.random() - 0.5) * 200;
                
                // 创建流星警告
                this.createMeteorWarning(targetX, targetY);
                
                // 1.5秒后造成伤害（更快的打击）
                setTimeout(() => {
                    this.createMeteorImpact(targetX, targetY);
                }, 1500);
                
            }, i * 300);
        }
        
        console.log('💀 BOSS召唤流星暴雨！');
    }
    
    // 进入愤怒模式
    enterEnragedMode() {
        if (this.state === 'enraged') return;
        
        this.state = 'enraged';
        this.speed *= 1.5;
        this.damage *= 1.3;
        this.attackCooldown *= 0.7;
        
        // 重置所有技能冷却
        Object.keys(this.skillCooldowns).forEach(skill => {
            this.skillCooldowns[skill] = 0;
        });
        
        console.log('💀💀💀 BOSS进入愤怒模式！！！');
    }
    
    // 阶段更新
    updatePhase() {
        const healthPercent = this.health / this.maxHealth;
        let newPhase = 1;
        
        if (healthPercent <= 0.75) newPhase = 2;
        if (healthPercent <= 0.5) newPhase = 3;
        if (healthPercent <= 0.25) newPhase = 4;
        
        if (newPhase > this.phase && !this.phaseTransitioning) {
            this.startPhaseTransition(newPhase);
        }
    }
    
    startPhaseTransition(newPhase) {
        this.phaseTransitioning = true;
        this.phaseTransitionTime = 3000; // 3秒转换时间
        this.isInvulnerable = true;
        
        console.log(`💀 BOSS进入第${newPhase}阶段！`);
        
        // 阶段转换特效
        this.createPhaseTransitionEffect();
        
        setTimeout(() => {
            this.phase = newPhase;
            this.phaseTransitioning = false;
            this.isInvulnerable = false;
            
            // 阶段升级奖励
            this.applyPhaseBonus(newPhase);
        }, 3000);
    }
    
    applyPhaseBonus(phase) {
        const hellModeMultiplier = this.isHellMode ? 1.5 : 1.0; // 地狱模式加成倍数
        
        switch (phase) {
            case 2:
                this.teleportCharges = this.isHellMode ? 5 : 3;
                if (this.isHellMode) {
                    // 地狱模式额外奖励血量
                    const bonusHealth = Math.floor(this.maxHealth * 0.15);
                    this.health += bonusHealth;
                    this.maxHealth += bonusHealth;
                    console.log(`🔥 地狱模式阶段2：额外获得${bonusHealth}血量！`);
                }
                break;
            case 3:
                this.speed *= (1.2 * hellModeMultiplier);
                this.teleportCharges = this.isHellMode ? 8 : 5;
                if (this.isHellMode) {
                    // 地狱模式额外能力
                    this.attackCooldown = Math.floor(this.attackCooldown * 0.7); // 攻击速度再次提升
                    const bonusHealth = Math.floor(this.maxHealth * 0.20);
                    this.health += bonusHealth;
                    this.maxHealth += bonusHealth;
                    console.log(`🔥 地狱模式阶段3：攻击速度大幅提升，额外获得${bonusHealth}血量！`);
                }
                break;
            case 4:
                this.damage *= (1.3 * hellModeMultiplier);
                this.teleportCharges = this.isHellMode ? 12 : 8;
                if (this.isHellMode) {
                    // 地狱模式终极增强
                    this.maxMinions = Math.floor(this.maxMinions * 1.5);
                    this.maxClones = Math.floor(this.maxClones * 1.5);
                    const bonusHealth = Math.floor(this.maxHealth * 0.25);
                    this.health += bonusHealth;
                    this.maxHealth += bonusHealth;
                    // 激活狂暴模式
                    this.berserkMode = true;
                    this.aura.color = '#FF0000';
                    this.aura.alpha = 1.0;
                    console.log(`🔥🔥 地狱模式阶段4：进入狂暴状态！召唤物和分身数量大增，额外获得${bonusHealth}血量！`);
                }
                break;
        }
        
        // 地狱模式所有阶段都获得技能冷却减少
        if (this.isHellMode) {
            Object.keys(this.baseCooldowns).forEach(skill => {
                this.baseCooldowns[skill] = Math.floor(this.baseCooldowns[skill] * 0.8);
            });
            console.log('🔥 地狱模式：所有技能冷却时间进一步减少！');
        }
    }
    
    // 工具方法
    getDistanceToPlayer(player) {
        return Math.sqrt(
            Math.pow(this.x - player.x, 2) + Math.pow(this.y - player.y, 2)
        );
    }
    
    moveTowardsPlayer(deltaTime, player) {
        const dx = player.x - this.x;
        const dy = player.y - this.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        
        if (distance > 0) {
            const moveSpeed = this.speed * (deltaTime / 1000);
            this.x += (dx / distance) * moveSpeed;
            this.y += (dy / distance) * moveSpeed;
        }
    }
    
    dealDamageToPlayer(player, damage) {
        if (player && typeof player.takeDamage === 'function') {
            player.takeDamage(damage);
        }
    }
    
    takeDamage(damage) {
        // 检查是否应该取消无敌状态
        const currentTime = Date.now();
        
        // 如果BOSS spawning超过3秒，强制取消无敌
        if (this.isInvulnerable && this.state === 'spawning' && 
            currentTime - this.spawnTime > this.spawnDuration) {
            this.isInvulnerable = false;
            this.state = 'active';
        }
        
        // 如果在阶段转换中超过5秒，强制取消无敌
        if (this.isInvulnerable && this.phaseTransitioning && 
            this.phaseTransitionTime <= 0) {
            this.isInvulnerable = false;
            this.phaseTransitioning = false;
        }
        
        // 如果BOSS状态是active但仍然无敌，强制取消无敌
        if (this.isInvulnerable && this.state === 'active') {
            this.isInvulnerable = false;
        }
        
        if (this.isInvulnerable) {
            return false;
        }
        
        // 应用抗性
        const stats = this.getBossStats(this.type);
        if (stats.resistances && stats.resistances.physical) {
            damage *= (1 - stats.resistances.physical);
        }
        
        this.health -= damage;
        
        if (this.health <= 0) {
            this.state = 'dying';
        }
        
        return true;
    }
    
    // 特效方法
    createShockwaveEffect(x, y, radius) {
        if (window.gameEngine && window.gameEngine.particles) {
            for (let i = 0; i < 20; i++) {
                const angle = (i / 20) * Math.PI * 2;
                const particle = {
                    x: x,
                    y: y,
                    vx: Math.cos(angle) * 150,
                    vy: Math.sin(angle) * 150,
                    life: 1000,
                    maxLife: 1000,
                    color: '#FF6600',
                    size: 4,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        this.vx *= 0.95;
                        this.vy *= 0.95;
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(255, 102, 0, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size * alpha, 0, Math.PI * 2);
                        ctx.fill();
                    }
                };
                window.gameEngine.particles.push(particle);
            }
        }
    }
    
    // 超级冲击波特效（增强版） - 已禁用红色圆圈效果
    createSuperShockwaveEffect(x, y, radius) {
        // 禁用红色冲击波特效 - 这是造成红色圆圈的源头之一
        return;
        /*
        if (window.gameEngine && window.gameEngine.particles) {
            // 更多更绚丽的粒子
            for (let i = 0; i < 40; i++) {
                const angle = (i / 40) * Math.PI * 2;
                const speed = 200 + Math.random() * 100;
                const particle = {
                    x: x,
                    y: y,
                    vx: Math.cos(angle) * speed,
                    vy: Math.sin(angle) * speed,
                    life: 1500,
                    maxLife: 1500,
                    color: '#FF0000',
                    size: 6 + Math.random() * 4,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        this.vx *= 0.92;
                        this.vy *= 0.92;
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(255, 0, 0, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size * alpha, 0, Math.PI * 2);
                        ctx.fill();
                        
                        // 添加外圈光晕
                        ctx.globalAlpha = alpha * 0.3;
                        ctx.fillStyle = '#FFD700';
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size * alpha * 2, 0, Math.PI * 2);
                        ctx.fill();
                        ctx.globalAlpha = 1;
                    }
                };
                window.gameEngine.particles.push(particle);
            }
        */
    }
    
    createTeleportEffect(x, y) {
        if (window.gameEngine && window.gameEngine.particles) {
            for (let i = 0; i < 15; i++) {
                const particle = {
                    x: x + (Math.random() - 0.5) * 60,
                    y: y + (Math.random() - 0.5) * 60,
                    vx: (Math.random() - 0.5) * 100,
                    vy: (Math.random() - 0.5) * 100,
                    life: 800,
                    maxLife: 800,
                    color: '#9966FF',
                    size: 6,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(153, 102, 255, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                        ctx.fill();
                    }
                };
                window.gameEngine.particles.push(particle);
            }
        }
    }
    
    createMeteorWarning(x, y) {
        // 禁用红色圆圈警告效果 - 这是造成红色圆圈的主要源头
        return;
        /*
        // 创建警告区域特效（红色圆圈）
        if (window.gameEngine && window.gameEngine.particles) {
            const warning = {
                x: x,
                y: y,
                radius: 40,
                life: 2000,
                maxLife: 2000,
                color: '#FF0000',
                update: function(deltaTime) {
                    this.life -= deltaTime;
                    return this.life > 0;
                },
                render: function(ctx) {
                    const alpha = 0.3 + Math.sin(Date.now() / 100) * 0.2;
                    ctx.strokeStyle = `rgba(255, 0, 0, ${alpha})`;
                    ctx.lineWidth = 3;
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
                    ctx.stroke();
                }
            };
            window.gameEngine.particles.push(warning);
        }
        */
    }
    
    createMeteorImpact(x, y) {
        // 造成范围伤害
        if (window.player) {
            const distToPlayer = Math.sqrt(
                Math.pow(x - window.player.x, 2) + Math.pow(y - window.player.y, 2)
            );
            if (distToPlayer < 40) {
                this.dealDamageToPlayer(window.player, this.damage * 1.5);
            }
        }
        
        // 创建爆炸特效
        if (window.gameEngine && window.gameEngine.particles) {
            for (let i = 0; i < 25; i++) {
                const angle = (i / 25) * Math.PI * 2;
                const speed = 50 + Math.random() * 100;
                const particle = {
                    x: x,
                    y: y,
                    vx: Math.cos(angle) * speed,
                    vy: Math.sin(angle) * speed,
                    life: 1500,
                    maxLife: 1500,
                    color: '#FF4400',
                    size: 3 + Math.random() * 4,
                    update: function(deltaTime) {
                        this.x += this.vx * deltaTime / 1000;
                        this.y += this.vy * deltaTime / 1000;
                        this.life -= deltaTime;
                        this.vy += 50 * deltaTime / 1000; // 重力
                        return this.life > 0;
                    },
                    render: function(ctx) {
                        const alpha = this.life / this.maxLife;
                        ctx.fillStyle = `rgba(255, 68, 0, ${alpha})`;
                        ctx.beginPath();
                        ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                        ctx.fill();
                    }
                };
                window.gameEngine.particles.push(particle);
            }
        }
    }
    
    addBossProjectile(projectile) {
        try {
            // 增强BOSS使用更安全的投射物添加方式
            if (window.gameEngine && typeof window.gameEngine.addZombieProjectile === 'function') {
                // 为BOSS投射物添加特殊标记
                const enhancedProjectile = {
                    ...projectile,
                    isBossProjectile: true,
                    bossPhase: this.phase,
                    priority: 'high' // 高优先级，不会被轻易清理
                };
                
                const success = window.gameEngine.addZombieProjectile(enhancedProjectile);
                if (!success) {
                    console.warn('增强BOSS投射物添加失败，可能投射物数组已满');
                }
                return success;
            } else {
                console.warn('游戏引擎投射物系统不可用');
                return false;
            }
        } catch (error) {
            console.error('增强BOSS投射物添加错误:', error);
            return false;
        }
    }
    
    createMinion(x, y) {
        // 创建一个简化的小僵尸
        return new Zombie(x, y, 'normal', 2);
    }
    
    updateMinions(deltaTime, player) {
        // 清理死亡的召唤物
        this.minions = this.minions.filter(minion => minion.health > 0);
        this.clones = this.clones.filter(clone => {
            const age = Date.now() - clone.creationTime;
            return clone.health > 0 && age < clone.lifespan;
        });
    }
    
    updateAnimations(deltaTime) {
        this.animationTime += deltaTime;
        this.animationFrame = Math.floor(this.animationTime / 200) % 4;
        
        // 更新光环 - 更动态的效果
        this.aura.radius = 60 + Math.sin(this.animationTime / 500) * 20;
        this.aura.alpha = 0.3 + Math.sin(this.animationTime / 300) * 0.2;
        
        // 呼吸效果 - BOSS体型轻微变化
        this.breathingScale = 1.0 + Math.sin(this.animationTime / 800) * 0.05;
        
        // 漂浮效果 - BOSS上下漂浮
        this.floatOffset = Math.sin(this.animationTime / 1000) * 3;
        
        // 眼部闪烁
        this.eyeBlinkTimer += deltaTime;
        if (this.eyeBlinkTimer > 3000 + Math.random() * 2000) {
            this.eyesOpen = false;
            setTimeout(() => { this.eyesOpen = true; }, 150);
            this.eyeBlinkTimer = 0;
        }
        
        // 阴影脉冲
        this.shadowPulse = Math.sin(this.animationTime / 400) * 0.3;
        
        // 更新血滴效果
        this.updateBloodDrops(deltaTime);
        
        // 更新能量粒子
        this.updateEnergyParticles(deltaTime);
        
        // 战斗时的特殊动画
        if (this.state === 'attacking') {
            this.size = 50 + Math.sin(this.animationTime / 100) * 5; // 攻击时震动
        }
        
        // 愤怒状态下的红色脉冲
        if (this.state === 'enraged') {
            this.aura.color = `hsl(${Math.sin(this.animationTime / 200) * 60}, 100%, 50%)`;
        }
    }
    
    updateBloodDrops(deltaTime) {
        // 当血量低于50%时，产生血滴特效
        if (this.health < this.maxHealth * 0.5) {
            if (Math.random() < 0.3) {
                this.bloodDrops.push({
                    x: this.x + (Math.random() - 0.5) * this.size,
                    y: this.y - this.size/2,
                    vx: (Math.random() - 0.5) * 50,
                    vy: Math.random() * 100 + 50,
                    life: 1000,
                    maxLife: 1000
                });
            }
        }
        
        // 更新现有血滴
        this.bloodDrops = this.bloodDrops.filter(drop => {
            drop.x += drop.vx * deltaTime / 1000;
            drop.y += drop.vy * deltaTime / 1000;
            drop.life -= deltaTime;
            return drop.life > 0;
        });
    }
    
    updateEnergyParticles(deltaTime) {
        // 在特殊状态下产生能量粒子
        if (this.state === 'special' || this.phase >= 3) {
            if (Math.random() < 0.5) {
                this.energyParticles.push({
                    x: this.x + (Math.random() - 0.5) * this.size * 2,
                    y: this.y + (Math.random() - 0.5) * this.size * 2,
                    vx: (Math.random() - 0.5) * 80,
                    vy: (Math.random() - 0.5) * 80,
                    life: 2000,
                    maxLife: 2000,
                    color: this.phase >= 4 ? '#FF00FF' : '#00FFFF'
                });
            }
        }
        
        // 更新现有粒子
        this.energyParticles = this.energyParticles.filter(particle => {
            particle.x += particle.vx * deltaTime / 1000;
            particle.y += particle.vy * deltaTime / 1000;
            particle.life -= deltaTime;
            return particle.life > 0;
        });
    }
    
    createPhaseTransitionEffect() {
        // 这里可以添加震撼的转换特效
    }
    
    handlePhaseTransition(deltaTime) {
        this.phaseTransitionTime -= deltaTime;
        // 转换期间可以添加特殊动画
    }
    
    handleAttackState(deltaTime, player) {
        // 攻击状态的具体实现
        this.performMeleeAttack(player);
        this.state = 'active';
    }
    
    handleSpecialState(deltaTime, player) {
        // 特殊攻击状态
        const actions = this.getAvailableActions().filter(a => a !== 'attack' && a !== 'move');
        if (actions.length > 0) {
            const action = actions[Math.floor(Math.random() * actions.length)];
            this.executeAction(action, player);
        }
        this.state = 'active';
    }
    
    handleEnragedState(deltaTime, player) {
        // 愤怒状态：更激进的行为
        if (this.stateTimer > 1000) { // 更频繁的行动
            const actions = this.getAvailableActions();
            const action = actions[Math.floor(Math.random() * actions.length)];
            this.executeAction(action, player);
            this.stateTimer = 0;
        }
        
        // 在愤怒状态下持续移动
        this.moveTowardsPlayer(deltaTime, player);
    }
    
    changeMovementPattern() {
        const patterns = ['chase', 'circle', 'retreat'];
        this.movementMode = patterns[Math.floor(Math.random() * patterns.length)];
        console.log(`💀 BOSS改变移动模式: ${this.movementMode}`);
    }
    
    checkDeath() {
        if (this.health <= 0 && this.state !== 'dying') {
            this.state = 'dying';
            console.log('💀💀💀 BOSS被击败！！！');
            
            // 创建死亡特效
            this.createDeathEffect();
        }
    }
    
    createDeathEffect() {
        console.log('💀 创建BOSS死亡特效');
        // 这里可以添加壮观的死亡特效
    }
    
    render(ctx) {
        try {
            if (!ctx) return;
            
            ctx.save();
            
            // 应用漂浮效果
            ctx.translate(this.x, this.y + this.floatOffset);
            
            // 应用呼吸缩放效果
            ctx.scale(this.breathingScale, this.breathingScale);
            
            // 绘制阴影脉冲
            this.renderShadow(ctx);
            
            // 绘制光环
            this.renderAura(ctx);
            
            // 绘制血滴特效
            this.renderBloodDrops(ctx);
            
            // 绘制能量粒子
            this.renderEnergyParticles(ctx);
            
            // 绘制BOSS主体
            this.renderBossBody(ctx);
            
            // 绘制血条
            this.renderHealthBar(ctx);
            
            // 绘制阶段指示器
            this.renderPhaseIndicator(ctx);
            
            ctx.restore();
            
            // 绘制分身
            this.renderClones(ctx);
            
        } catch (error) {
            console.error('BOSS渲染失败:', error);
        }
    }
    
    renderShadow(ctx) {
        // 绘制动态阴影
        ctx.save();
        ctx.globalAlpha = 0.3 + this.shadowPulse;
        ctx.fillStyle = '#000000';
        ctx.translate(0, this.size + 10);
        ctx.scale(1.2, 0.5);
        ctx.beginPath();
        ctx.arc(0, 0, this.size, 0, Math.PI * 2);
        ctx.fill();
        ctx.restore();
    }
    
    renderBloodDrops(ctx) {
        // 绘制血滴特效
        this.bloodDrops.forEach(drop => {
            const alpha = drop.life / drop.maxLife;
            ctx.save();
            ctx.globalAlpha = alpha;
            ctx.fillStyle = '#8B0000';
            ctx.translate(drop.x - this.x, drop.y - this.y);
            ctx.beginPath();
            ctx.arc(0, 0, 2, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }
    
    renderEnergyParticles(ctx) {
        // 绘制能量粒子
        this.energyParticles.forEach(particle => {
            const alpha = particle.life / particle.maxLife;
            ctx.save();
            ctx.globalAlpha = alpha;
            ctx.fillStyle = particle.color;
            ctx.translate(particle.x - this.x, particle.y - this.y);
            ctx.beginPath();
            ctx.arc(0, 0, 3, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }
    
    renderAura(ctx) {
        // 动态光环颜色基于BOSS状态和阶段
        let auraColor = this.aura.color;
        if (this.state === 'enraged') {
            auraColor = '#FF4500'; // 愤怒时橙红色
        } else if (this.phase >= 4) {
            auraColor = '#8A2BE2'; // 第4阶段紫色
        } else if (this.phase >= 3) {
            auraColor = '#DC143C'; // 第3阶段深红色
        } else if (this.phase >= 2) {
            auraColor = '#FF6347'; // 第2阶段番茄红
        }
        
        // 解析颜色值
        const color = this.hexToRgb(auraColor);
        const rgb = `${color.r}, ${color.g}, ${color.b}`;
        
        const gradient = ctx.createRadialGradient(0, 0, 0, 0, 0, this.aura.radius);
        gradient.addColorStop(0, `rgba(${rgb}, 0)`);
        gradient.addColorStop(0.5, `rgba(${rgb}, ${this.aura.alpha * 0.2})`);
        gradient.addColorStop(0.8, `rgba(${rgb}, ${this.aura.alpha * 0.4})`);
        gradient.addColorStop(1, `rgba(${rgb}, ${this.aura.alpha})`);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(0, 0, this.aura.radius, 0, Math.PI * 2);
        ctx.fill();
        
        // 外环脉冲效果
        if (this.state === 'special' || this.phase >= 3) {
            ctx.save();
            ctx.globalAlpha = this.aura.alpha * 0.3;
            ctx.strokeStyle = auraColor;
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.arc(0, 0, this.aura.radius + 10, 0, Math.PI * 2);
            ctx.stroke();
            ctx.restore();
        }
    }
    
    hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : {r: 139, g: 0, b: 0};
    }
    
    renderBossBody(ctx) {
        // 根据阶段渲染不同的恐怖造型
        switch (this.phase) {
            case 1:
                this.renderPhase1Boss(ctx);
                break;
            case 2:
                this.renderPhase2Boss(ctx);
                break;
            case 3:
                this.renderPhase3Boss(ctx);
                break;
            case 4:
                this.renderPhase4Boss(ctx);
                break;
            default:
                this.renderPhase1Boss(ctx);
        }
    }
    
    // 第1阶段：腐烂的校长僵尸
    renderPhase1Boss(ctx) {
        const baseColor = this.state === 'enraged' ? '#8B0000' : '#2F4F4F';
        
        // 主体 - 腐烂的身躯
        ctx.fillStyle = baseColor;
        ctx.fillRect(-this.size/2, -this.size/2, this.size, this.size * 1.2);
        
        // 腐烂斑点（固定位置，避免闪烁）
        ctx.fillStyle = '#556B2F';
        const spots = [
            {x: -20, y: -15}, {x: 15, y: -10}, {x: -8, y: 5},
            {x: 25, y: 8}, {x: -15, y: 20}, {x: 10, y: -25},
            {x: -25, y: 12}, {x: 18, y: -18}
        ];
        spots.forEach(spot => {
            ctx.fillRect(spot.x - 3, spot.y - 3, 6, 6);
        });
        
        // 校长西装（破烂）
        ctx.fillStyle = '#1C1C1C';
        ctx.fillRect(-this.size/2 + 8, -this.size/2 + 15, this.size - 16, this.size - 20);
        
        // 破烂的领带
        ctx.fillStyle = '#8B0000';
        ctx.fillRect(-8, -this.size/2 + 15, 16, 25);
        
        // 恐怖的脸
        ctx.fillStyle = '#8B7D6B';
        ctx.fillRect(-this.size/2 + 12, -this.size/2 + 8, this.size - 24, 20);
        
        // 动态眼睛效果
        if (this.eyesOpen) {
            // 血红眼睛
            ctx.fillStyle = '#FF0000';
            ctx.fillRect(-20, -this.size/2 + 12, 8, 8);
            ctx.fillRect(12, -this.size/2 + 12, 8, 8);
            
            // 发光瞳孔（带脉冲效果）
            const pupilGlow = 0.5 + Math.sin(this.animationTime / 300) * 0.3;
            ctx.fillStyle = `rgba(255, 255, 0, ${pupilGlow})`;
            ctx.fillRect(-18, -this.size/2 + 14, 4, 4);
            ctx.fillRect(14, -this.size/2 + 14, 4, 4);
            
            // 眼睛发光效果
            ctx.save();
            ctx.shadowColor = '#FF0000';
            ctx.shadowBlur = 8;
            ctx.fillStyle = '#FFFF00';
            ctx.fillRect(-18, -this.size/2 + 14, 4, 4);
            ctx.fillRect(14, -this.size/2 + 14, 4, 4);
            ctx.restore();
        } else {
            // 闭眼状态 - 绘制眼线
            ctx.fillStyle = '#8B7D6B';
            ctx.fillRect(-20, -this.size/2 + 16, 8, 2);
            ctx.fillRect(12, -this.size/2 + 16, 8, 2);
        }
        
        // 张开的大嘴（露出獠牙）
        ctx.fillStyle = '#000000';
        ctx.fillRect(-16, -this.size/2 + 25, 32, 10);
        
        // 尖牙
        ctx.fillStyle = '#FFFFFF';
        for (let i = 0; i < 6; i++) {
            const toothX = -14 + i * 5;
            ctx.fillRect(toothX, -this.size/2 + 25, 2, 6);
        }
    }
    
    // 第2阶段：变异增大的恐怖形态
    renderPhase2Boss(ctx) {
        const mutationSize = this.size * 1.1;
        const baseColor = this.state === 'enraged' ? '#8B0000' : '#2F2F2F';
        
        // 变异的身体 - 更大更扭曲
        ctx.fillStyle = baseColor;
        ctx.save();
        ctx.scale(1.1, 1.2); // 扭曲形状
        ctx.fillRect(-mutationSize/2, -mutationSize/2, mutationSize, mutationSize);
        ctx.restore();
        
        // 突起的肌肉块
        ctx.fillStyle = '#8B0000';
        const musclePositions = [
            {x: -25, y: -20}, {x: 25, y: -20}, 
            {x: -30, y: 0}, {x: 30, y: 0},
            {x: -20, y: 25}, {x: 20, y: 25}
        ];
        musclePositions.forEach(pos => {
            ctx.beginPath();
            ctx.arc(pos.x, pos.y, 8, 0, Math.PI * 2);
            ctx.fill();
        });
        
        // 多个眼睛（变异特征）
        const eyePositions = [
            {x: -20, y: -15}, {x: 0, y: -20}, {x: 20, y: -15},
            {x: -25, y: 5}, {x: 25, y: 5}
        ];
        eyePositions.forEach(pos => {
            // 眼球
            ctx.fillStyle = '#FF0000';
            ctx.beginPath();
            ctx.arc(pos.x, pos.y, 6, 0, Math.PI * 2);
            ctx.fill();
            
            // 瞳孔
            ctx.fillStyle = '#FFFF00';
            ctx.beginPath();
            ctx.arc(pos.x, pos.y, 3, 0, Math.PI * 2);
            ctx.fill();
        });
        
        // 咆哮的大嘴
        ctx.fillStyle = '#000000';
        ctx.fillRect(-25, 10, 50, 15);
        
        // 更多更大的獠牙（固定高度）
        ctx.fillStyle = '#FFFFFF';
        const fangHeights = [6, 8, 5, 9, 7, 6, 8, 5]; // 固定的獠牙高度
        for (let i = 0; i < 8; i++) {
            const fangX = -22 + i * 6;
            const fangHeight = fangHeights[i];
            ctx.fillRect(fangX, 10, 3, fangHeight);
        }
        
        // 滴血效果
        ctx.fillStyle = '#8B0000';
        for (let i = 0; i < 5; i++) {
            const dropX = -20 + i * 10;
            ctx.fillRect(dropX, 25, 2, 8);
        }
    }
    
    // 第3阶段：恶魔化形态
    renderPhase3Boss(ctx) {
        const demonSize = this.size * 1.2;
        
        // 恶魔般的身体 - 更加扭曲
        ctx.fillStyle = this.state === 'enraged' ? '#8B0000' : '#4B0000';
        ctx.save();
        ctx.scale(1.2, 1.3);
        ctx.fillRect(-demonSize/2, -demonSize/2, demonSize, demonSize);
        ctx.restore();
        
        // 恶魔角
        ctx.fillStyle = '#2F2F2F';
        // 左角
        ctx.beginPath();
        ctx.moveTo(-25, -this.size/2 - 10);
        ctx.lineTo(-15, -this.size/2 - 25);
        ctx.lineTo(-20, -this.size/2 - 5);
        ctx.closePath();
        ctx.fill();
        
        // 右角
        ctx.beginPath();
        ctx.moveTo(25, -this.size/2 - 10);
        ctx.lineTo(15, -this.size/2 - 25);
        ctx.lineTo(20, -this.size/2 - 5);
        ctx.closePath();
        ctx.fill();
        
        // 燃烧的眼睛
        ctx.fillStyle = '#FF4500';
        ctx.beginPath();
        ctx.arc(-18, -15, 10, 0, Math.PI * 2);
        ctx.arc(18, -15, 10, 0, Math.PI * 2);
        ctx.fill();
        
        // 火焰瞳孔
        ctx.fillStyle = '#FFFF00';
        ctx.beginPath();
        ctx.arc(-18, -15, 6, 0, Math.PI * 2);
        ctx.arc(18, -15, 6, 0, Math.PI * 2);
        ctx.fill();
        
        // 火焰效果（眼睛周围）
        ctx.fillStyle = '#FF6600';
        for (let i = 0; i < 16; i++) {
            const angle = (i / 16) * Math.PI * 2;
            const flameX = -18 + Math.cos(angle) * 12;
            const flameY = -15 + Math.sin(angle) * 12;
            ctx.fillRect(flameX - 1, flameY - 1, 2, 4);
        }
        
        // 巨大的獠牙嘴
        ctx.fillStyle = '#000000';
        ctx.fillRect(-30, 0, 60, 20);
        
        // 巨型獠牙
        ctx.fillStyle = '#FFFFFF';
        const bigFangs = [
            {x: -25, w: 4, h: 12},
            {x: -15, w: 3, h: 8},
            {x: -5, w: 4, h: 10},
            {x: 5, w: 4, h: 10},
            {x: 15, w: 3, h: 8},
            {x: 25, w: 4, h: 12}
        ];
        bigFangs.forEach(fang => {
            ctx.fillRect(fang.x, 0, fang.w, fang.h);
        });
        
        // 恶魔爪子
        ctx.fillStyle = '#2F2F2F';
        // 左爪
        for (let i = 0; i < 3; i++) {
            ctx.fillRect(-this.size/2 - 8 + i * 3, -10 + i * 8, 2, 15);
        }
        // 右爪
        for (let i = 0; i < 3; i++) {
            ctx.fillRect(this.size/2 + 2 + i * 3, -10 + i * 8, 2, 15);
        }
    }
    
    // 第4阶段：终极恶魔领主形态
    renderPhase4Boss(ctx) {
        const lordSize = this.size * 1.3;
        
        // 恶魔领主的身体 - 最大最恐怖
        const bodyGradient = ctx.createRadialGradient(0, 0, 0, 0, 0, lordSize);
        bodyGradient.addColorStop(0, this.state === 'enraged' ? '#FF0000' : '#8B0000');
        bodyGradient.addColorStop(0.7, '#2F2F2F');
        bodyGradient.addColorStop(1, '#000000');
        
        ctx.fillStyle = bodyGradient;
        ctx.save();
        ctx.scale(1.3, 1.4);
        ctx.fillRect(-lordSize/2, -lordSize/2, lordSize, lordSize);
        ctx.restore();
        
        // 巨大的恶魔角（分叉）
        ctx.fillStyle = '#1C1C1C';
        // 左角 - 分叉
        ctx.beginPath();
        ctx.moveTo(-30, -this.size/2 - 15);
        ctx.lineTo(-20, -this.size/2 - 35);
        ctx.lineTo(-15, -this.size/2 - 30);
        ctx.lineTo(-25, -this.size/2 - 10);
        ctx.closePath();
        ctx.fill();
        
        ctx.beginPath();
        ctx.moveTo(-22, -this.size/2 - 32);
        ctx.lineTo(-12, -this.size/2 - 40);
        ctx.lineTo(-18, -this.size/2 - 35);
        ctx.closePath();
        ctx.fill();
        
        // 右角 - 分叉
        ctx.beginPath();
        ctx.moveTo(30, -this.size/2 - 15);
        ctx.lineTo(20, -this.size/2 - 35);
        ctx.lineTo(15, -this.size/2 - 30);
        ctx.lineTo(25, -this.size/2 - 10);
        ctx.closePath();
        ctx.fill();
        
        ctx.beginPath();
        ctx.moveTo(22, -this.size/2 - 32);
        ctx.lineTo(12, -this.size/2 - 40);
        ctx.lineTo(18, -this.size/2 - 35);
        ctx.closePath();
        ctx.fill();
        
        // 地狱火眼睛
        const eyeGradient = ctx.createRadialGradient(-20, -20, 0, -20, -20, 15);
        eyeGradient.addColorStop(0, '#FFFF00');
        eyeGradient.addColorStop(0.5, '#FF4500');
        eyeGradient.addColorStop(1, '#8B0000');
        
        ctx.fillStyle = eyeGradient;
        ctx.beginPath();
        ctx.arc(-20, -20, 12, 0, Math.PI * 2);
        ctx.arc(20, -20, 12, 0, Math.PI * 2);
        ctx.fill();
        
        // 火焰瞳孔
        ctx.fillStyle = '#FFFFFF';
        ctx.beginPath();
        ctx.arc(-20, -20, 4, 0, Math.PI * 2);
        ctx.arc(20, -20, 4, 0, Math.PI * 2);
        ctx.fill();
        
        // 围绕眼睛的地狱火
        for (let eye of [{x: -20, y: -20}, {x: 20, y: -20}]) {
            for (let i = 0; i < 20; i++) {
                const angle = (i / 20) * Math.PI * 2;
                const radius = 15 + Math.sin(Date.now() / 100 + i) * 3;
                const flameX = eye.x + Math.cos(angle) * radius;
                const flameY = eye.y + Math.sin(angle) * radius;
                
                ctx.fillStyle = i % 2 === 0 ? '#FF4500' : '#FF6600';
                ctx.fillRect(flameX - 1, flameY - 1, 2, 6);
            }
        }
        
        // 第三只眼（额头）
        ctx.fillStyle = '#8B0000';
        ctx.beginPath();
        ctx.arc(0, -35, 8, 0, Math.PI * 2);
        ctx.fill();
        
        ctx.fillStyle = '#FFFF00';
        ctx.beginPath();
        ctx.arc(0, -35, 4, 0, Math.PI * 2);
        ctx.fill();
        
        // 终极恶魔嘴 - 巨大而恐怖
        ctx.fillStyle = '#000000';
        ctx.fillRect(-40, -5, 80, 25);
        
        // 多层獠牙
        ctx.fillStyle = '#FFFFFF';
        // 外层大獠牙
        const outerFangs = [
            {x: -35, w: 5, h: 15},
            {x: -20, w: 4, h: 12},
            {x: -5, w: 5, h: 18},
            {x: 5, w: 5, h: 18},
            {x: 20, w: 4, h: 12},
            {x: 35, w: 5, h: 15}
        ];
        outerFangs.forEach(fang => {
            ctx.fillRect(fang.x, -5, fang.w, fang.h);
        });
        
        // 内层小獠牙
        ctx.fillStyle = '#F0F0F0';
        for (let i = 0; i < 12; i++) {
            const fangX = -30 + i * 5;
            ctx.fillRect(fangX, 5, 2, 8);
        }
        
        // 恶魔翅膀轮廓
        ctx.strokeStyle = '#2F2F2F';
        ctx.lineWidth = 4;
        
        // 左翅膀
        ctx.beginPath();
        ctx.moveTo(-this.size/2 - 20, -20);
        ctx.quadraticCurveTo(-this.size/2 - 40, -30, -this.size/2 - 35, 0);
        ctx.quadraticCurveTo(-this.size/2 - 45, 20, -this.size/2 - 25, 15);
        ctx.stroke();
        
        // 右翅膀
        ctx.beginPath();
        ctx.moveTo(this.size/2 + 20, -20);
        ctx.quadraticCurveTo(this.size/2 + 40, -30, this.size/2 + 35, 0);
        ctx.quadraticCurveTo(this.size/2 + 45, 20, this.size/2 + 25, 15);
        ctx.stroke();
        
        // 恶魔爪子 - 更大更尖锐
        ctx.fillStyle = '#1C1C1C';
        // 左爪
        for (let i = 0; i < 4; i++) {
            ctx.fillRect(-this.size/2 - 12 + i * 4, -15 + i * 10, 3, 20);
        }
        // 右爪
        for (let i = 0; i < 4; i++) {
            ctx.fillRect(this.size/2 + 4 + i * 4, -15 + i * 10, 3, 20);
        }
        
        // 地狱火光环效果
        if (this.state === 'enraged') {
            ctx.strokeStyle = '#FF4500';
            ctx.lineWidth = 3;
            ctx.beginPath();
            ctx.arc(0, 0, lordSize + 10, 0, Math.PI * 2);
            ctx.stroke();
            
            ctx.strokeStyle = '#FF6600';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(0, 0, lordSize + 15, 0, Math.PI * 2);
            ctx.stroke();
        }
    }
    
    renderHealthBar(ctx) {
        const barWidth = 120;
        const barHeight = 12;
        const barY = -this.size - 25;
        
        // 背景
        ctx.fillStyle = 'rgba(255, 255, 255, 0.3)';
        ctx.fillRect(-barWidth/2, barY, barWidth, barHeight);
        
        // 血量
        const healthPercent = this.health / this.maxHealth;
        let healthColor = '#00FF00';
        if (healthPercent < 0.6) healthColor = '#FFFF00';
        if (healthPercent < 0.3) healthColor = '#FF0000';
        
        ctx.fillStyle = healthColor;
        ctx.fillRect(-barWidth/2, barY, barWidth * healthPercent, barHeight);
        
        // 边框
        ctx.strokeStyle = '#FFFFFF';
        ctx.lineWidth = 2;
        ctx.strokeRect(-barWidth/2, barY, barWidth, barHeight);
        
        // 血量文字
        ctx.fillStyle = '#FFFFFF';
        ctx.font = 'bold 10px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`${this.health}/${this.maxHealth}`, 0, barY - 5);
    }
    
    renderPhaseIndicator(ctx) {
        // 阶段指示器
        const indicatorY = -this.size - 45;
        
        ctx.fillStyle = '#FFD700';
        ctx.font = 'bold 14px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`第${this.phase}阶段`, 0, indicatorY);
        
        // 阶段星星
        for (let i = 0; i < this.phase; i++) {
            const starX = (i - (this.phase - 1) / 2) * 15;
            ctx.fillStyle = '#FFD700';
            ctx.beginPath();
            ctx.moveTo(starX, indicatorY - 15);
            ctx.lineTo(starX + 3, indicatorY - 9);
            ctx.lineTo(starX + 9, indicatorY - 9);
            ctx.lineTo(starX + 4, indicatorY - 5);
            ctx.lineTo(starX + 6, indicatorY + 1);
            ctx.lineTo(starX, indicatorY - 2);
            ctx.lineTo(starX - 6, indicatorY + 1);
            ctx.lineTo(starX - 4, indicatorY - 5);
            ctx.lineTo(starX - 9, indicatorY - 9);
            ctx.lineTo(starX - 3, indicatorY - 9);
            ctx.closePath();
            ctx.fill();
        }
    }
    
    renderClones(ctx) {
        this.clones.forEach(clone => {
            ctx.save();
            ctx.translate(clone.x, clone.y);
            
            // 分身稍微透明
            ctx.globalAlpha = 0.7;
            
            // 分身主体
            ctx.fillStyle = '#4B0000';
            ctx.beginPath();
            ctx.arc(0, 0, clone.radius, 0, Math.PI * 2);
            ctx.fill();
            
            ctx.restore();
        });
    }
}